<template>

    <el-dialog
            :title="!dataForm.id ? '新增' : '修改'"
            :close-on-click-modal="false"
            :visible.sync="visible">
        <el-form :model="dataForm" :rules="dataRule" ref="dataForm"
                 label-width="80px">
            <el-form-item label="章节名" prop="chapterName">
                <el-input v-model="dataForm.chapterName" placeholder="章节名"></el-input>
            </el-form-item>
            <el-form-item label="内容" prop="content">
                <summer-note v-model="dataForm.content" :summerNoteVal="summerNoteVal"/>
            </el-form-item>
            <el-form-item label="是否展示" prop="isShow">
                <el-switch
                        v-model="dataForm.isShow"
                        :active-value="1"
                        :inactive-value="0"
                        active-color="#13ce66"
                        inactive-color="#ff4949">
                </el-switch>
            </el-form-item>
            <el-form-item label="序号" prop="orderNumber">
                <el-input-number v-model="dataForm.orderNumber" controls-position="right"
                                 :min="1"></el-input-number>
            </el-form-item>
            <el-form-item label="浏览次数" prop="watchTime">
                <el-input-number v-model="dataForm.watchTime" controls-position="right"
                                 :min="1"></el-input-number>
            </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
            <el-button @click="visible = false">取消</el-button>
            <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
        </span>
    </el-dialog>

</template>

<script>

    import SummerNote from "@/components/SummerNote";
    import {getUUID} from "../../../utils";
    import Cookies from "js-cookie";

    export default {
        components: {SummerNote},
        data() {
            return {
                activeNames: ['1'],
                visible: false,
                dataForm: {
                    id: 0,
                    infoId: 0,
                    chapterName: '',
                    content: '',
                    isShow: 0,
                    watchTime: 0,
                    orderNumber: 0,
                },
                dataRule: {
                    author: [
                        {required: true, message: '章节名不能为空', trigger: 'blur'}
                    ],
                    title: [
                        {required: true, message: '内容不能为空', trigger: 'blur'}
                    ],
                },

                signData: {
                    policy: '',
                    signature: '',
                    key: '',
                    ossaccessKeyId: '',
                    accessKeyId: '',
                    dir: '',
                    host: '',
                },
                fileList: [],
                uploadUrl: this.global.fileUrl, //上传文件路径

                //富文本编辑点
                summerNoteVal: "",

            }
        },
        methods: {
            init(id, articleId) {
                this.fileList = [];
                this.summerNoteVal = "";
                this.dataForm.id = id || 0
                this.dataForm.infoId = articleId
                this.visible = true
                this.$nextTick(() => {
                    this.$refs['dataForm'].resetFields()
                    if (this.dataForm.id) {
                        this.$api.Chapter.info(this.dataForm.id).then((data) => {
                            if (data && data.code === 0) {
                                this.dataForm.infoId = data.chapter.infoId
                                this.dataForm.chapterName = data.chapter.chapterName
                                this.dataForm.content = data.chapter.content
                                this.dataForm.isShow = data.chapter.isShow
                                this.dataForm.content = data.chapter.content
                                this.dataForm.watchTime = data.chapter.watchTime
                                this.dataForm.orderNumber = data.chapter.orderNumber

                                this.summerNoteVal = this.dataForm.content;

                                //重置分类数组 用于级联展示
                                this.getCatIds();
                            }
                        })
                    }
                })
            },

            //重置分类数组 用于级联展示
            getCatIds() {

                let _self = this;
                const key = this.dataForm.catId;
                let arrTemp = []; //中间记录使用

                exec(this.catList);

                function exec(catListChidren) {
                    catListChidren.map(cat => {
                        arrTemp.push(cat.id);
                        if (cat.children && cat.children.length > 0) {
                            exec(cat.children)
                            arrTemp.pop()
                        } else {
                            if (cat.id == key) {
                                _self.dataForm.catIds = [...arrTemp];
                            } else {
                                arrTemp.pop()
                            }
                        }
                    })
                }

            },


            // 表单提交
            dataFormSubmit() {
                var contentNew;
                let _self = this;
                this.$refs['dataForm'].validate((valid) => {
                    if (valid) {

                        //1、执行点、开始执行
                        exec();

                        //2、设定同步操作 await 在 async 函数中生效
                        // await 操作符用于等待一个 Promise 对象 - 待 promise - resolve执行后，放行
                        async function exec() {
                            //3、执行img检测，base64转http
                            await execCheckImgBase64()
                            //4、执行保存、修改操作 - 必须等全部遍历结束后执行
                            console.log("开始执行文章保存操作");
                            saveInfo();
                        }

                        //3-1、检测文章中base64格式的图片 - 初始化文章内容
                        function execCheckImgBase64() {
                            let content = _self.dataForm.content;
                            contentNew = content;
                            return checkImgBase64(content);
                        }


                        //当没有图片时，直接卡住了问题
                        let isRunUpload = false; //设定变量管控，是否有对文章图片进行操作过

                        //3-2、提取base64图片，每次执行获取检测获取一次base图片 - resolve需要在最后一次执行时放行
                        function checkImgBase64(content) {
                            let img_s_img = "<img";
                            let img_s_src = "src=\"";
                            let img_e = "\"";

                            if (content.indexOf(img_s_img) != -1) {
                                let temp = content.substring(content.indexOf(img_s_src) + img_s_src.length); // <img开始后面字符串
                                let temp_img = temp.substring(0, temp.indexOf(img_e)); //截取img <> 中间
                                let temp_img_without = temp.substring(temp.indexOf(img_e)); //截取后剩余字符串
                                // let f = this.imgBase64ToFile(temp_img,"1111");
                                if (temp_img.startsWith("data:image")) {
                                    isRunUpload = true;

                                    //3-2-2 、遍历最后的检测：检测执行这次上传图片操作时，是不是最后一次上传。 两种情况：
                                    // 1、剩余里面不包含 <img
                                    // 2、剩余里面有 <img 但是没有base64图片
                                    let lastUpload = temp_img_without.indexOf(img_s_img) == -1
                                            || (temp_img_without.indexOf(img_s_img) != -1
                                                    && temp_img_without.indexOf("data:image") == -1);

                                    //3-2-1操作具体的base64编码 - 要求同步顺序执行
                                    console.log("3-2-1操作具体的base64编码 - uploadImgBaseAction -s-------");
                                    return uploadImgBaseAction(temp_img, lastUpload).then((lastUpload) => {
                                        if (lastUpload) {
                                            return new Promise((resolve => {
                                                resolve();
                                            }))
                                        }
                                        return checkImgBase64(temp_img_without);
                                    });
                                }
                                // http格式的img 不执行，继续循环
                                return checkImgBase64(temp_img_without);

                            }

                            //执行最外围的异步放行操作 - 当没有图片时，执行的放行操作
                            if (!isRunUpload) {
                                return new Promise((resolve => {
                                    resolve();
                                }))
                            }
                        }

                        // 3-2-1-1异步操作：保存base64 图片 =》 修订，必须是顺序的，保存可异步
                        function uploadImgBaseAction(imgBase64, lastUpload) {
                            return getPolicy(imgBase64, (resolve) => {
                                //3-2-1-3、执行上传图片

                                let form = new FormData();
                                form.append('ossaccessKeyId', _self.signData.ossaccessKeyId);
                                form.append('accessKeyId', _self.signData.accessKeyId);
                                form.append('policy', _self.signData.policy);
                                form.append('signature', _self.signData.signature);
                                form.append('key', _self.signData.key);
                                form.append('dir', _self.signData.dir);
                                form.append('host', _self.signData.host);

                                // 上传图片
                                form.append('file', dataURLtoBlob(imgBase64));
                                let req = new XMLHttpRequest();
                                req.open('post', _self.uploadUrl, false);

                                let token = Cookies.get('token');
                                req.setRequestHeader("token", token)

                                console.log("3-2-1-3、执行上传图片 - req.send(form);");
                                req.send(form);

                                //替换内容
                                contentNew = contentNew.replace(imgBase64, _self.uploadUrl + '/' + _self.signData.key);
                                _self.dataForm.content = contentNew;

                                console.log("3-2-1-3、替换内容 - {}", contentNew);
                                resolve(lastUpload);
                                //执行上传操作
                                // callBackSaveOperation();

                            })
                        }

                        //3-2-1-2 、获取签名 获取签名后在执行
                        function getPolicy(imgBase64, callBack) {
                            return new Promise((resolve) => {
                                _self.$api.File.ossPolicy().then((data) => {
                                    if (data && data.code === 0) {

                                        _self.signData.ossaccessKeyId = data.data.accessid;
                                        _self.signData.accessKeyId = data.data.accessid;
                                        _self.signData.policy = data.data.policy;
                                        _self.signData.signature = data.data.signature;
                                        _self.signData.key = data.data.dir + getUUID()
                                                + `.${imgBase64.substring(imgBase64.indexOf("image/") + 6, imgBase64.indexOf(";base64,"))}`;
                                        _self.signData.dir = data.data.dir;
                                        _self.signData.host = data.data.host;
                                        _self.signData.expire = data.data.expire;


                                        callBack(resolve);

                                    } else {
                                        _self.$message.error(data.msg)
                                    }
                                })
                            });

                        }

                        //转换base
                        function dataURLtoBlob(dataurl) {
                            var arr = dataurl.split(','),
                                    mime = arr[0].match(/:(.*?);/)[1],
                                    bstr = atob(arr[1]),
                                    n = bstr.length,
                                    u8arr = new Uint8Array(n);
                            while (n--) {
                                u8arr[n] = bstr.charCodeAt(n);
                            }
                            return new Blob([u8arr], {
                                type: mime
                            });
                        }

                        //上传数据
                        function saveInfo() {
                            let data = {
                                'id': _self.dataForm.id || undefined,
                                'infoId': _self.dataForm.infoId,
                                'chapterName': _self.dataForm.chapterName,
                                'content': _self.dataForm.content,
                                'isShow': _self.dataForm.isShow,
                                'watchTime': _self.dataForm.watchTime,
                                'orderNumber': _self.dataForm.orderNumber,
                            };
                            let resultAction;
                            if (!_self.dataForm.id) {
                                resultAction = _self.$api.Chapter.save(data);
                            } else {
                                resultAction = _self.$api.Chapter.update(data);
                            }

                            resultAction.then((data) => {
                                if (data && data.code === 0) {
                                    _self.$message({
                                        message: '操作成功',
                                        type: 'success',
                                        duration: 1500,
                                        onClose: () => {
                                            _self.visible = false
                                            _self.$emit('refreshDataList')
                                        }
                                    })

                                    //关闭确定框
                                    _self.visible = false
                                    _self.$emit('refreshDataList')

                                } else {
                                    _self.$message.error(data.msg)
                                }
                            })
                        }

                    }
                })
            },

            //上传前操作-获取签名
            beforeUpload(file) {
                let _self = this;
                let filename = file.name;

                return new Promise((resolve, reject) => {
                    this.$api.File.ossPolicy().then((data) => {
                        if (data && data.code === 0) {

                            _self.signData.ossaccessKeyId = data.data.accessid;
                            _self.signData.accessKeyId = data.data.accessid;
                            _self.signData.policy = data.data.policy;
                            _self.signData.signature = data.data.signature;
                            _self.signData.key = data.data.dir + getUUID() + `_${filename}`;
                            _self.signData.dir = data.data.dir;
                            _self.signData.host = data.data.host;
                            _self.signData.expire = data.data.expire;
                            resolve();
                        } else {
                            this.$message.error(data.msg)
                            reject();
                        }
                    })

                });
            },
            handleRemove(file, fileList) {
                console.log("handleRemove");
                console.log(file, fileList);
            },
            handleSuccess(response, file, fileList) {
                this.dataForm.showImg = this.uploadUrl + '/' + this.signData.key;
            },

            getContent() {
                this.dialogVisible = true
                this.ue.ready(() => {
                    this.ueContent = this.ue.getContent()
                })
            },

        }
    }
</script>
